﻿<!-- Views/Employee/TakeExam.cshtml - 继续加大填空题文本框宽度 -->

@model WebApplication1.Models.Exam

@{
    ViewBag.Title = "参加考试 - " + Model.ExamName;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container-fluid px-0">
    <!-- 考试头部信息 -->
    <div class="exam-header bg-primary text-white p-3 sticky-top">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h5 class="mb-1">@Model.ExamName</h5>
                <small>第 <span id="currentQuestion">1</span> 题 / 共 @Model.Questions.Where(x=>x.IsActive).ToList().Count 题</small>
            </div>
            <div class="text-end">
                <div class="timer-display fw-bold" id="time">@Model.Duration:00</div>
                <small>剩余时间</small>
            </div>
        </div>
        <div class="progress mt-2">
            <div class="progress-bar" role="progressbar" id="progressBar" style="width: 0%"></div>
        </div>
    </div>

    @using (Html.BeginForm("SubmitExam", "Employee", FormMethod.Post, new { id = "examForm" }))
    {
        @Html.Hidden("examId", Model.ExamId)

        <!-- 题目容器 -->
        <div class="questions-container" id="questionsContainer">
            @{
                var shuffledQuestions = Model.Questions.Where(x => x.IsActive).OrderBy(x => Guid.NewGuid()).ToList();
            }

            @for (int i = 0; i < shuffledQuestions.Count; i++)
            {
                var question = shuffledQuestions[i];
                <div class="question-page @(i == 0 ? "active" : "")" data-question-index="@i" id="question_@i">
                    <div class="question-content p-3">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <span class="badge bg-primary">第 @(i + 1) 题</span>
                                <span class="badge bg-success ms-2">@question.Score 分</span>
                            </div>
                            <div>
                                @if (question.QuestionType == "Single")
                                {
                                    <span class="badge bg-info">单选</span>
                                }
                                else if (question.QuestionType == "Multiple")
                                {
                                    <span class="badge bg-success">多选</span>
                                }
                                else if (question.QuestionType == "TrueFalse")
                                {
                                    <span class="badge bg-warning">判断</span>
                                }
                                else if (question.QuestionType == "Fill")
                                {
                                    <span class="badge bg-danger">填空</span>
                                }
                            </div>
                        </div>

                        <div class="question-text mb-4">
                            <p class="fw-bold fs-6 mb-0">@question.QuestionText</p>
                        </div>

                        @if (question.QuestionType == "Fill")
                        {
                            <!-- 填空题输入框 - 进一步增大文本框 -->
                            <div class="form-group mb-4">
                                <label class="form-label fw-bold mb-2">请填写答案：</label>
                                <textarea class="form-control form-control-lg fill-answer-textarea"
                                          name="question_@question.QuestionId"
                                          rows="4"
                                          placeholder="请输入答案，多个答案请用逗号分隔"></textarea>
                                <div class="form-text text-muted mt-2">
                                    <i class="glyphicon glyphicon-info-sign me-1"></i>
                                    示例：答案1,答案2,答案3
                                </div>
                            </div>
                        }
                        else if (question.QuestionType == "Single")
                        {
                            {
                                // 单选题选项随机打乱
                                var optionList = question.Options.OrderBy(o => o.OptionLabel).ToList();
                                var shuffledOptionIndices = Enumerable.Range(0, optionList.Count).OrderBy(x => Guid.NewGuid()).ToList();

                                // 计算打乱顺序后的正确答案
                                var originalCorrectAnswer = question.CorrectAnswer;
                                var newCorrectAnswer = "";
                                var newCorrectAnswerText = "";

                                for (int k = 0; k < optionList.Count; k++)
                                {
                                    var originalIndex = shuffledOptionIndices[k];
                                    var originalOptionLabel = optionList[originalIndex].OptionLabel;

                                    if (originalOptionLabel == originalCorrectAnswer)
                                    {
                                        newCorrectAnswer = ((char)('A' + k)).ToString();
                                        newCorrectAnswerText = optionList[originalIndex].OptionText;
                                        break;
                                    }
                                }
                                ViewBag.newCorrectAnswer = newCorrectAnswer;
                                ViewBag.newCorrectAnswerText = newCorrectAnswerText;
                                ViewBag.optionList = optionList;
                                ViewBag.shuffledOptionIndices = shuffledOptionIndices;
                            }
                            <!-- 保存打乱顺序后的正确答案序号和选项描述 -->
                            @Html.Hidden("correct_" + question.QuestionId, (string)ViewBag.newCorrectAnswer)
                            @Html.Hidden("correct_text_" + question.QuestionId, (string)ViewBag.newCorrectAnswerText)

                            <div class="options-container mb-4">
                                @for (int j = 0; j < ViewBag.optionList.Count; j++)
                                {
                                    var optionIndex = ViewBag.shuffledOptionIndices[j];
                                    var option = ViewBag.optionList[optionIndex];
                                    var displayLabel = ((char)('A' + j)).ToString();
                                    <div class="custom-option custom-option-radio mb-3">
                                        <input type="radio"
                                               name="question_@question.QuestionId"
                                               id="q@(question.QuestionId)_@displayLabel"
                                               value="@displayLabel"
                                               class="custom-option-input"
                                               data-display-label="@displayLabel"
                                               data-option-text="@option.OptionText" />
                                        <label class="custom-option-label"
                                               for="q@(question.QuestionId)_@displayLabel">
                                            <span class="custom-option-marker">
                                                <span class="custom-option-marker-inner"></span>
                                            </span>
                                            <span class="custom-option-text">
                                                <span class="badge bg-secondary me-2">@displayLabel</span>
                                                <span>@option.OptionText</span>
                                            </span>
                                        </label>
                                    </div>
                                }
                            </div>
                        }
                        else if (question.QuestionType == "Multiple")
                        {
                            {
                                // 多选题选项随机打乱
                                var optionList = question.Options.OrderBy(o => o.OptionLabel).ToList();
                                var shuffledOptionIndices = Enumerable.Range(0, optionList.Count).OrderBy(x => Guid.NewGuid()).ToList();

                                // 计算打乱顺序后的正确答案
                                var originalCorrectAnswers = question.CorrectAnswer.Split(',').ToList();
                                var newCorrectAnswers = new List<string>();
                                var newCorrectAnswerTexts = new List<string>();

                                for (int k = 0; k < optionList.Count; k++)
                                {
                                    var originalIndex = shuffledOptionIndices[k];
                                    var originalOptionLabel = optionList[originalIndex].OptionLabel;

                                    if (originalCorrectAnswers.Contains(originalOptionLabel))
                                    {
                                        var newLabel = ((char)('A' + k)).ToString();
                                        newCorrectAnswers.Add(newLabel);
                                        newCorrectAnswerTexts.Add(optionList[originalIndex].OptionText);
                                    }
                                }

                                var newCorrectAnswerString = string.Join(",", newCorrectAnswers);
                                var newCorrectAnswerTextString = string.Join(";", newCorrectAnswerTexts);

                                ViewBag.newCorrectAnswerString = newCorrectAnswerString;
                                ViewBag.newCorrectAnswerTextString = newCorrectAnswerTextString;
                                ViewBag.optionList1 = optionList;
                                ViewBag.shuffledOptionIndices1 = shuffledOptionIndices;
                            }
                            <!-- 保存打乱顺序后的正确答案序号和选项描述 -->
                            @Html.Hidden("correct_" + question.QuestionId, (string)ViewBag.newCorrectAnswerString)
                            @Html.Hidden("correct_text_" + question.QuestionId, (string)ViewBag.newCorrectAnswerTextString)

                            <div class="options-container mb-4">
                                @for (int j = 0; j < ViewBag.optionList1.Count; j++)
                                {
                                    var optionIndex = ViewBag.shuffledOptionIndices1[j];
                                    var option = ViewBag.optionList1[optionIndex];
                                    var displayLabel = ((char)('A' + j)).ToString();
                                    <div class="custom-option custom-option-checkbox mb-3">
                                        <input type="checkbox"
                                               name="question_@question.QuestionId"
                                               id="q@(question.QuestionId)_@displayLabel"
                                               value="@displayLabel"
                                               class="custom-option-input"
                                               data-display-label="@displayLabel"
                                               data-option-text="@option.OptionText" />
                                        <label class="custom-option-label"
                                               for="q@(question.QuestionId)_@displayLabel">
                                            <span class="custom-option-marker">
                                                <span class="custom-option-marker-inner"></span>
                                            </span>
                                            <span class="custom-option-text">
                                                <span class="badge bg-secondary me-2">@displayLabel</span>
                                                <span>@option.OptionText</span>
                                            </span>
                                        </label>
                                    </div>
                                }
                            </div>
                        }
                        else if (question.QuestionType == "TrueFalse")
                        {
                            {
                                // 判断题正确答案
                                var correctAnswer = question.CorrectAnswer == "True" ? "T" : "F";
                                var correctAnswerText = question.CorrectAnswer == "True" ? "正确" : "错误";

                                ViewBag.correctAnswer = correctAnswer;
                                ViewBag.correctAnswerText = correctAnswerText;
                            }
                            <!-- 保存判断题的正确答案和描述 -->
                            @Html.Hidden("correct_" + question.QuestionId, (string)ViewBag.correctAnswer)
                            @Html.Hidden("correct_text_" + question.QuestionId, (string)ViewBag.correctAnswerText)

                            <div class="options-container mb-4">
                                <div class="custom-option custom-option-radio mb-3">
                                    <input type="radio"
                                           name="question_@question.QuestionId"
                                           id="q@(question.QuestionId)_T"
                                           value="T"
                                           class="custom-option-input"
                                           data-display-label="正确" />
                                    <label class="custom-option-label"
                                           for="q@(question.QuestionId)_T">
                                        <span class="custom-option-marker">
                                            <span class="custom-option-marker-inner"></span>
                                        </span>
                                        <span class="custom-option-text">
                                            <i class="glyphicon glyphicon-ok-circle text-success me-2"></i>
                                            <span>正确</span>
                                        </span>
                                    </label>
                                </div>
                                <div class="custom-option custom-option-radio mb-3">
                                    <input type="radio"
                                           name="question_@question.QuestionId"
                                           id="q@(question.QuestionId)_F"
                                           value="F"
                                           class="custom-option-input"
                                           data-display-label="错误" />
                                    <label class="custom-option-label"
                                           for="q@(question.QuestionId)_F">
                                        <span class="custom-option-marker">
                                            <span class="custom-option-marker-inner"></span>
                                        </span>
                                        <span class="custom-option-text">
                                            <i class="glyphicon glyphicon-remove-circle text-danger me-2"></i>
                                            <span>错误</span>
                                        </span>
                                    </label>
                                </div>
                            </div>
                        }

                        <!-- 答案显示文本框 -->
                        <!--<div class="answer-display mb-3">
    <label class="form-label fw-bold">您的答案：</label>
    <input type="text" class="form-control answer-textbox"
           id="answer_@question.QuestionId"
           readonly
           placeholder="请选择或填写答案" />-->
                        <!-- 隐藏字段保存用户答案的文字描述 -->
                        @Html.Hidden("answer_text_" + question.QuestionId, "", new { @class = "answer-text-hidden" })
                        <!--</div>-->
                        <!-- 显示该题的正确答案（打乱顺序后的） -->
                        <!--<div class="correct-answer-display bg-success bg-opacity-10 p-3 rounded mb-3">
        <div class="d-flex align-items-center">
            <i class="glyphicon glyphicon-ok-circle text-success me-2"></i>
            <strong>正确答案：</strong>
            <span class="ms-2 fw-bold text-success" id="correct_answer_艾特question.QuestionId">
            //    艾特{
            //        if (question.QuestionType == "Single")
            //        {
            //            艾特ViewBag.newCorrectAnswer<text> - </text>艾特ViewBag.newCorrectAnswerText
            //        }
            //        else if (question.QuestionType == "Multiple")
            //        {
            //            艾特ViewBag.newCorrectAnswerString<text> - </text>艾特ViewBag.newCorrectAnswerTextString.Replace(";", " , ")
            //        }
            //        else if (question.QuestionType == "TrueFalse")
            //        {
            //            (ViewBag.correctAnswer == "T" ? "正确" : "错误")
            //        }
            //        else
            //        {
            //            艾特question.CorrectAnswer
            //        }
            //    }
            </span>
        </div>
    </div>-->
                    </div>
                </div>
            }
        </div>

        <!-- 导航按钮 -->
        <div class="exam-navigation bg-light p-3 border-top fixed-bottom">
            <div class="d-flex justify-content-between">
                <button type="button" class="btn btn-outline-secondary" id="prevBtn" disabled>
                    <i class="glyphicon glyphicon-chevron-left"></i> 上一题
                </button>
                <button type="button" class="btn btn-primary" id="nextBtn">
                    下一题 <i class="glyphicon glyphicon-chevron-right"></i>
                </button>
                <button type="submit" class="btn btn-success d-none" id="submitBtn">
                    <i class="glyphicon glyphicon-send"></i> 提交试卷
                </button>
            </div>
        </div>
    }
</div>
<!-- 确保正确的脚本加载顺序 -->
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<style>
    body {
        padding-bottom: 80px; /* 为底部导航留出空间 */
    }

    .exam-header {
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 1000;
    }

    .question-page {
        display: none;
    }

        .question-page.active {
            display: block;
        }

    .question-content {
        min-height: calc(100vh - 180px);
    }

    .exam-navigation {
        box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        z-index: 1000;
    }

    /* 自定义选项样式 */
    .custom-option {
        position: relative;
        display: block;
    }

    .custom-option-input {
        position: absolute;
        opacity: 0;
        cursor: pointer;
        height: 0;
        width: 0;
    }

    .custom-option-label {
        display: flex;
        align-items: flex-start;
        padding: 15px 20px;
        background-color: #fff;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;
        margin-bottom: 0;
    }

        .custom-option-label:hover {
            border-color: #667eea;
            background-color: #f0f4ff;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
        }

    .custom-option-input:checked + .custom-option-label {
        border-color: #667eea;
        background-color: #f0f4ff;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
    }

    .custom-option-marker {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 20px;
        height: 20px;
        margin-right: 15px;
        border: 2px solid #adb5bd;
        border-radius: 50%;
        transition: all 0.2s ease;
        flex-shrink: 0;
        margin-top: 2px;
    }

    .custom-option-input:checked + .custom-option-label .custom-option-marker {
        border-color: #667eea;
        background-color: #667eea;
    }

    .custom-option-marker-inner {
        display: block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: transparent;
        transition: all 0.2s ease;
    }

    .custom-option-input:checked + .custom-option-label .custom-option-marker-inner {
        background-color: #fff;
    }

    /* 多选框样式 */
    .custom-option-checkbox .custom-option-marker {
        border-radius: 4px;
    }

    .custom-option-checkbox .custom-option-marker-inner {
        width: 10px;
        height: 10px;
        border-radius: 2px;
        clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);
    }

    .custom-option-checkbox .custom-option-input:checked + .custom-option-label .custom-option-marker-inner {
        background-color: #fff;
        clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);
    }

    .custom-option-text {
        flex: 1;
        font-weight: 500;
        color: #495057;
    }

    .custom-option-input:checked + .custom-option-label .custom-option-text {
        color: #667eea;
        font-weight: 600;
    }

    .answer-textbox {
        background-color: #f8f9fa;
        border: 2px solid #667eea;
        font-weight: 600;
        color: #667eea;
    }

    .correct-answer-display {
        border-left: 4px solid #198754;
    }

    .timer-display {
        font-size: 1.2rem;
    }

    .progress {
        height: 8px;
    }

    .progress-bar {
        transition: width 0.3s ease;
    }

    /* 填空题文本框优化 - 进一步加大宽度和高度 */
    .fill-answer-textarea {
        min-height: 120px;
        resize: vertical;
        font-size: 1rem;
        padding: 15px;
        width: 100%;
        box-sizing: border-box;
        border-width: 2px;
    }

        .fill-answer-textarea:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.25);
        }

    /* 响应式调整 */
    @@media (max-width: 576px) {
        .exam-header {
            padding: 10px;
        }

        .question-content {
            padding: 15px;
        }

        .custom-option-label {
            padding: 12px 15px;
        }

        .btn {
            padding: 0.5rem 0.75rem;
            font-size: 0.9rem;
        }

        .fill-answer-textarea {
            min-height: 100px;
            font-size: 0.9rem;
            padding: 12px;
        }
    }

    @@media (min-width: 577px) and (max-width: 768px) {
        .fill-answer-textarea {
            min-height: 110px;
            font-size: 0.95rem;
            padding: 13px;
        }
    }

    @@media (min-width: 769px) {
        .fill-answer-textarea {
            min-height: 130px;
            font-size: 1.05rem;
            padding: 16px;
        }
    }

    textarea {
        max-width: 100%;
    }
</style>

<script>
    $(document).ready(function() {
        let currentQuestionIndex = 0;
        const totalQuestions = @Model.Questions.Where(x => x.IsActive).ToList().Count;
        let timeLeft = @Model.Duration * 60; // 转换为秒

        // 更新进度显示
        function updateProgress() {
            const progress = ((currentQuestionIndex + 1) / totalQuestions) * 100;
            $('#progressBar').css('width', progress + '%');
            $('#currentQuestion').text(currentQuestionIndex + 1);
        }

        // 显示当前题目
        function showQuestion(index) {
            $('.question-page').removeClass('active');
            $('#question_' + index).addClass('active');
            currentQuestionIndex = index;
            updateProgress();

            // 更新按钮状态
            $('#prevBtn').prop('disabled', index === 0);
            if (index === totalQuestions - 1) {
                $('#nextBtn').addClass('d-none');
                $('#submitBtn').removeClass('d-none');
            } else {
                $('#nextBtn').removeClass('d-none');
                $('#submitBtn').addClass('d-none');
            }
        }

        // 更新答案显示和隐藏字段
        function updateAnswerDisplay(questionId) {
            const selectedValues = [];
            const selectedTexts = [];
            const questionPage = $('#question_' + questionId.replace('question_', ''));
            const questionInputs = $('[name="question_' + questionId + '"]');
            const questionType = questionInputs.first().attr('type') || (questionInputs.first().is('textarea') ? 'textarea' : 'unknown');

            if (questionType === 'radio') {
                const selected = $('input[name="question_' + questionId + '"]:checked');
                if (selected.length > 0) {
                    const displayLabel = selected.data('display-label');
                    const optionText = selected.data('option-text') || selected.closest('.custom-option').find('.custom-option-text').text().replace(displayLabel + '.', '').trim();
                    selectedValues.push(displayLabel);
                    selectedTexts.push(optionText);
                }
            } else if (questionType === 'checkbox') {
                $('input[name="question_' + questionId + '"]:checked').each(function() {
                    const displayLabel = $(this).data('display-label');
                    const optionText = $(this).data('option-text') || $(this).closest('.custom-option').find('.custom-option-text').text().replace(displayLabel + '.', '').trim();
                    selectedValues.push(displayLabel);
                    selectedTexts.push(optionText);
                });
            } else {
                // 填空题
                const fillValue = $('textarea[name="question_' + questionId + '"], input[name="question_' + questionId + '"]').val();
                if (fillValue) {
                    selectedValues.push(fillValue);
                    selectedTexts.push(fillValue);
                }
            }

            $('#answer_' + questionId).val(selectedValues.join(', '));
            $('#answer_text_' + questionId).val(selectedTexts.join('; '));
        }

        // 单选题点击事件
        $(document).on('change', 'input[type="radio"]', function() {
            const questionId = $(this).attr('name').replace('question_', '');
            updateAnswerDisplay(questionId);
        });

        // 多选题点击事件
        $(document).on('change', 'input[type="checkbox"]', function() {
            const questionId = $(this).attr('name').replace('question_', '');
            updateAnswerDisplay(questionId);
        });

        // 填空题输入事件
        $(document).on('input', 'textarea[name^="question_"], input[name^="question_"]', function() {
            const questionId = $(this).attr('name').replace('question_', '');
            updateAnswerDisplay(questionId);
        });

        // 下一题
        $('#nextBtn').click(function() {
            if (currentQuestionIndex < totalQuestions - 1) {
                showQuestion(currentQuestionIndex + 1);
            }
        });

        // 上一题
        $('#prevBtn').click(function() {
            if (currentQuestionIndex > 0) {
                showQuestion(currentQuestionIndex - 1);
            }
        });

        // 考试计时器
        var timerElement = document.getElementById("time");
        var timer = setInterval(function() {
            timeLeft--;
            var minutes = Math.floor(timeLeft / 60);
            var seconds = timeLeft % 60;
            timerElement.textContent = minutes + ":" + (seconds < 10 ? "0" : "") + seconds;

            // 时间快到时改变颜色
            if (timeLeft <= 300) { // 5分钟
                $('.exam-header').removeClass('bg-primary').addClass('bg-danger');
            }

            // 时间到自动提交
            if (timeLeft <= 0) {
                clearInterval(timer);
                alert("考试时间到，试卷将自动提交！");
                document.getElementById("examForm").submit();
            }
        }, 1000);

        // 提交确认
        $('#examForm').submit(function(e) {
            if (!confirm('确定要提交试卷吗？提交后无法修改答案。')) {
                e.preventDefault();
            }
        });

        // 初始化
        updateProgress();

        // 初始化答案显示
        $('.question-page').each(function() {
            const questionId = $(this).find('[name^="question_"]').first().attr('name').replace('question_', '');
            updateAnswerDisplay(questionId);
        });
    });
</script>